﻿using StockHelper.Scripts.Comm;
using StockHelper.Scripts.Sound;
using StockHelper.Scripts.Stock;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using File = StockHelper.Scripts.Comm.File;

namespace StockHelper.Scripts
{
    public class Config
    {
        public static string voicesPath = @"voices/";
        public static string date;
        public static Hashtable global = null;
        private static readonly string configPath = "config\\config.json";
        public static readonly bool isDebug = true;

        /// <summary>播报间隔</summary>
        public static int voiceTime = 60;
        /// <summary>是否播报</summary>
        public static bool playVoice = true;
        /// <summary>播报音量</summary>
        public static float voiceVolume = 1;
        /// <summary>数据更新间隔</summary>
        public static int updataTime = 7;


        public static void Init() {

            File.Mkdir("config");

            if (File.Exists(configPath))
            {
                try
                {
                    global = (Hashtable)MiniJSON.jsonDecode(File.Take(configPath));
                }
                catch
                {
                    System.Windows.Forms.MessageBox.Show("配置文件异常");
                }
                if (global == null) {
                    global = (Hashtable)MiniJSON.jsonDecode(Comm.DefaultConfig.Config);
                    File.Save(configPath, Comm.DefaultConfig.Config);
                }
            }
            else
            {
                global = (Hashtable)MiniJSON.jsonDecode(Comm.DefaultConfig.Config);
                File.Save(configPath, Comm.DefaultConfig.Config);
            }

            
            foreach (string i in File.GetFiles(voicesPath, "json", SearchOption.AllDirectories)) {
                if (Path.GetFileName(i).ToLower() == "manifest.json") {
                    Hashtable hashtable = (Hashtable)MiniJSON.jsonDecode(File.Take(i));
                    if (hashtable == null) continue;
                    string dirPath = Path.GetDirectoryName(i).Replace(System.AppDomain.CurrentDomain.BaseDirectory, "") + "\\";
                    Hashtable keys = new Hashtable(), prices = new Hashtable();
                    foreach (Hashtable d in (ArrayList)hashtable["sounds"]) {
                        keys[d["key"].ToString()] = d;
                    }
                    foreach (Hashtable d in (ArrayList)hashtable["price"])
                    {
                        prices[d["key"].ToString()] = d;
                    }
                    Assets.packages.Add(new Assets.Package {
                        jsonPath = dirPath + Path.GetFileName(i),
                        path = dirPath,
                        voicePath = dirPath.Replace("voices\\", ""),
                        name = hashtable["name"].ToString(),
                        data = hashtable,
                        official = hashtable.ContainsKey("hashtable") &&  hashtable["author"].ToString() == "Aliong",
                        keys = keys,
                        price = prices,
                    });
                    hashtable = null;
                }
            }

        }
        

        /// <summary>
        /// 获取配置
        /// </summary>
        /// <param name="path"></param>
        /// <param name="t">默认</param>
        /// <returns></returns>
        public static object GetCfg(string path, object t) {
            Hashtable cfg = global;
            List<string> keys = path.Split('/').ToList();
            while (keys.Count > 1)
            {
                if (!cfg.ContainsKey(keys[0]))
                    cfg[keys[0]] = new Hashtable();
                cfg = cfg[keys[0]] as Hashtable;
                keys.RemoveAt(0);
            }
            if (cfg.ContainsKey(keys[0]))
                return cfg[keys[0]];
            cfg[keys[0]] = t;
            return t;
        }

        public static T Get<T>(string path, T t) {
            try
            {
                if (typeof(T) == typeof(string))
                    return (T)(object)GetCfg(path, t).ToString();
                if (typeof(T) == typeof(float))
                    return (T)(object)float.Parse(GetCfg(path, t).ToString());
                if (typeof(T) == typeof(int))
                    return (T)(object)int.Parse(GetCfg(path, t).ToString());
                else return (T)GetCfg(path, t);
            }
            catch (Exception e){
                Console.WriteLine(MiniJSON.jsonEncode(global));
                Console.WriteLine(path);
                Console.WriteLine(t.GetType().ToString());

                throw new Exception(e.ToString());
            }
        }

        public static void Save() {

            File.Save(configPath, MiniJSON.jsonEncode(global));

        }

        public static void Set(string path, object val) {
            Hashtable cfg = global;
            List<string> keys = path.Split('/').ToList();
            while (keys.Count > 1)
            {
                if (!cfg.ContainsKey(keys[0]))
                    cfg[keys[0]] = new Hashtable();
                cfg = cfg[keys[0]] as Hashtable;
                keys.RemoveAt(0);
            }
            cfg[keys[0]] = val;
            Save();
        }

    }
}
